package com.test.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.SneakyThrows;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * @author zxs
 * @since 2021/5/8
 */
public class NettyClient {

    private final int port;

    public NettyClient(int port) {
        this.port = port;
    }

    @SneakyThrows
    public void collect() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioSocketChannel.class).handler(new ClientHandler());
            ChannelFuture f = bootstrap.connect(new InetSocketAddress(port)).sync();
            f.channel().closeFuture().sync();
        } finally {
            System.out.println("client shutdown");
            group.shutdownGracefully();
        }
    }

    static class ClientHandler extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            socketChannel.pipeline()
                    .addLast(new LengthFieldPrepender(4))
                    .addLast(new StringEncoder())
                    .addLast(new HeartbeatHandler());
        }
    }


    static class HeartbeatHandler extends ChannelInboundHandlerAdapter{


        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            //添加心跳包
            ctx.executor().schedule(()->{
                ctx.writeAndFlush("heart beat").addListener((l)->{
                    System.out.println("send beat complete");
                });
            },5, TimeUnit.SECONDS);
            super.channelActive(ctx);
        }
    }

    public static void main(String[] args) {
        new NettyClient(8080).collect();
    }

}
